#include "twitter.h"
#include "ui_twitter.h"



Twitter::Twitter(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Twitter)
{
    ui->setupUi(this);
}

Twitter::~Twitter()
{
    delete ui;
}

void Twitter::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void Twitter::on_pushButton_released()
{   qDebug("Button pusehd");
    QNetworkAccessManager *manager  = new QNetworkAccessManager(this);
    QString name = ui->lineEdit->text();
    qDebug()<<name;
QString URL = "http://twitter.com/statuses/user_timeline/";
    URL.append(name);
    URL.append(".rss?count=5");
    //QUrl url("http://twitter.com/statuses/user_timeline/manikantan_k.rss?count=5");
    qDebug()<<URL;
    QUrl url(URL);
    qDebug()<<url.toString();
    QNetworkReply* reply = manager->get(QNetworkRequest(url));
    QObject::connect(manager, SIGNAL(finished(QNetworkReply*)),this, SLOT(replyFinished(QNetworkReply*)));
}

void Twitter::replyFinished(QNetworkReply * a ) {
    qDebug("replied");

    QString str (a->readAll());
    if(a->error() == QNetworkReply::NoError) {
        qDebug("No errors");
        xml.addData(str);
        parseXml();
    }
    else {
        qDebug("errors in reply");
    }
}
void Twitter::parseXml()
{   qDebug("Parsing Twitter Feed");
    QString currentTag;
    QStringList feedcontent;
    while (!xml.atEnd()) {
             xml.readNext();
             if (xml.isStartElement()) {

                 if (xml.name() == "item"){


                 }

                 currentTag = xml.name().toString();
             } else if (xml.isEndElement()) {
                  if (xml.name() == "item") {


                 }

             } else if (xml.isCharacters() && !xml.isWhitespace()) {
                 if (currentTag == "description")
                     //qDebug("sd %s", xml.text().toString());
                 {      qDebug()<<"Got"<< xml.text().toString();
                        feedcontent.append(xml.text().toString());
                 }
                    /* else if (currentTag == "link")
                         linkString += xml.text().toString();
                     else if (currentTag == "pubDate")
                         dateString += xml.text().toString();  */

             }
         }
         if (xml.error() && xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) {
             //qWarning() << "XML ERROR:" << xml.lineNumber() << ": " << xml.errorString();
             //http.abort();
         }
         ui->listView->setModel(new QStringListModel(feedcontent));
}
